package demo4.mapper;

import demo4.pojo.User;
import demo4.util.DBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**当我们创建Spring容器时，指定一个包后，除了该包内容外，子孙包也会扫描
 *
 *UserMapper该类就是和数据库中一个名为User的表进行操作的
 *  */
@Component
public class UserMapper implements IUserMapper{
    @Autowired
    private DBUtil dbUtil;

    public  int insert(User user) {
        System.out.println("UserMapper:插入用户数据");
        try (Connection connection = dbUtil.getConnection();){
            String sql = "INSERT INTO user(username,password,nickname,age)" +
                    "VALUES(?,?,?,?)";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3,user.getNickname());
            ps.setInt(4,user.getAge());
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int insert(demo1.User user) {
        return 0;
    }
}
